package com.hongdee.crm.taskConfig.service.impl;

import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.Constant;
import com.hongdee.crm.car.entity.TCrmCar;
import com.hongdee.crm.carConfig.entity.TCrmCarConf;
import com.hongdee.crm.carConfig.entity.TCrmCarConfExcelTemp;
import com.hongdee.crm.carConfig.service.ITcrmCarConfService;
import com.hongdee.crm.taskConfig.dao.ITCrmCarTaskConfDao;
import com.hongdee.crm.taskConfig.entity.TCrmCarTaskConf;
import com.hongdee.crm.taskConfig.service.ITCrmCarTaskConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by My on 2017/5/16.
 */
@Service
public class TCrmCarTaskConfServiceImpl implements ITCrmCarTaskConfService {

    @Autowired
    private ITCrmCarTaskConfDao taskConfDao;

    @Autowired
    private ITcrmCarConfService tcrmCarConfService;

    private enum FROM_CAR {
        NO, YES
    }

    private enum TASK_POWER {
        //        0管理 1是处理
        G, C
    }

    //---------------------------------------快修任务分配开始-------------------------------------------------------------
    /**
     * 保存任务分配资源 人员 区域 类型
     * 规则：
     * 1、不遵循车辆档案
     * 2、一个人可以负责多个区域，需要多次分配；
     * 3、一个人不可以在一个区域多次分配，只能分配一次；
     * 4、一个区域内只能使用一种分配类型，如全部 只能分一人；尾号、尾数、VIN只能是一种；
     * @param taskConf
     * @param uid
     * @param s
     */
    @Override
    public void saveTaskConf(TCrmCarTaskConf taskConf,String uid,String s) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        taskConf.setCompanyId(companyId);
        updTaskPcode(taskConf);
        /**
         * 处理权限
         */
        if (taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))) {
            //=================续保执行以下代码，按照门店分配==============================================================//
            if(taskConf.getTaskCCode().equals("xbj") || taskConf.getTaskCCode().equals("xbs")){ // 如果是续保交强或续保商业
                // 执行门店代码
                boolean storeFlag = checkTaskConfByStore(taskConf);
                if(storeFlag){ // 门店如果已经被分配
                    throw new Exception("一个门店不可以同时分配给两个人！");
                }
            }
            else {
                //=================非续保执行以下代码==========================================================//
                //1、判断该人员在该区域下已经有了分配资源
                boolean areaFlag=checkTaskConfByArea(taskConf,uid);
                if(!areaFlag){
                    //1、新增全部类型 判断是否已经存在全部
                    if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_ALL)) {
                        //判断是否有未分配任务类型
                        List list=null;
                        list=this.getTaskConfByArea(taskConf,uid,Constant.DISTCARTYPE.CAR_WFP);
                        if(list.size()>0){
                            throw new Exception("该区域下已存在[未分配]处理资源类型，如需要分配请调整后重新分配!!");
                        }
                        //判断是否已经有全部的分配类型
                        list=this.getTaskConfByArea(taskConf,uid,Constant.DISTCARTYPE.CAR_ALL);
                        if(list.size()>0){
                            throw new Exception("该区域下已经存在[全部]处理资源类型，如需要分配请调整后重新分配!!");
                        }
                    }
                    //3、分配未分配类别
                    if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WFP)) {
                        //1、判断是否有全部任务类别
                        List list=null;
                        list=this.getTaskConfByArea(taskConf,uid,Constant.DISTCARTYPE.CAR_ALL);
                        if(list.size()>0){
                            throw new Exception("该区域下已经存在[全部]处理资源类型，如需要分配请调整后重新分配!!");
                        }
                        //2、判断是否已经有未分配任务类别
                        list=this.getTaskConfByArea(taskConf,uid,Constant.DISTCARTYPE.CAR_WFP);
                        if(list.size()>0){
                            throw new Exception("该区域下已存在[未分配]处理资源类型，如需要分配请调整后重新分配!!");
                        }
                    }
                    //4、尾号、尾数、VIN
                    if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WH) ||
                            taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WS) ||
                            taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_VIN)) {
                        List list=null;
                        //判断是否已经有全部的分配类型
                        list=this.getTaskConfByArea(taskConf,uid,Constant.DISTCARTYPE.CAR_ALL);
                        if(list.size()>0){
                            throw new Exception("该区域下已经存在[全部]处理资源类型，如需要分配请调整后重新分配!!");
                        }
                        boolean flag=checkTaskConfByWHAndWSAndVinAdnArea(taskConf,Constant.DISTCARTYPE.CAR_WFP,companyId);
                        if (flag) {
                            throw new Exception("该任务类型下，已经存在其它任务资源，请调整后重新分配!!");
                        }
                    }
                }else{
                    throw new Exception("该人员已经在该区域下分配了任务资源，如需分配请调后重新分配!!!");
                }
                //=============================================================================================//
            }
        }
        saveTaskConfByArea(taskConf,uid);
    }

    /**
     * 保存任务分配资源信息
     *
     * @param taskConf
     * @param uid
     * @throws Exception
     */
    private void saveTaskConfByArea(TCrmCarTaskConf taskConf, String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        taskConf.setCompanyId(companyId);
        if (taskConf.getFromCar().equals(String.valueOf(FROM_CAR.NO.ordinal()))
                &&
                taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))
                ) {
            //验证是否有其它的
            switch (taskConf.getConfType()) {
                case Constant.DISTCARTYPE.CAR_WH:
                    //1、查看已经分配的数值是否有人已经分配
                    boolean flag = this.checkPlateNum(taskConf.getConfType(), taskConf.getConfVal(), taskConf.getuId(),
                            taskConf.getCompanyId(), taskConf.getTaskPCode(), taskConf.getTaskCCode(),taskConf.getoArea(),
                            taskConf.getoAreaSecond());
                    //2、没有分配保存车辆分配规则
                    if (flag) {
                        throw new Exception("该人员分配的车牌号已经存在，请调整后重新分配!!");
                    }
                    break;
                case Constant.DISTCARTYPE.CAR_WS:
                    boolean wsFlag = this.checkPlateNum(taskConf.getConfType(), taskConf.getConfVal(), taskConf.getuId(),
                            taskConf.getCompanyId(), taskConf.getTaskPCode(), taskConf.getTaskCCode(),taskConf.getoArea(),
                            taskConf.getoAreaSecond());
                    //2、没有分配保存车辆分配规则
                    if (wsFlag) {
                        throw new Exception("该人员分配的车牌号已经存在，请调整后重新分配!!");
                    }
                    break;
            }
        }
        taskConfDao.saveOrUpdate(taskConf);
//        this.distCarByCarConf(taskConf, uid, null);
    }

    public boolean checkPlateNum(String refType, String refValue, String userId, String companyId, String typePCode,
                                 String typeCCode,String area,String areaSecond) throws Exception {
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append(" select * from  T_CRM_TASK_CONF where company_id=? and conf_type=? and task_p_code=? and task_c_code=? and o_area=? and o_area_second=? ");
        params.add(companyId);
        params.add(refType);
        params.add(typePCode);
        params.add(typeCCode);
        params.add(area);
        params.add(areaSecond);
        if (!"".equals(userId)) {
            sqlStr.append(" and u_id<>? ");
            params.add(userId);
        }
        sqlStr.append(" and ( ");
        String[] refValues = refValue.split(",");
        for (int i = 0; i < refValues.length; i++) {
            sqlStr.append(" find_in_set(?,conf_val) ");
            params.add(refValues[i]);
            if (i < (refValues.length - 1)) {
                sqlStr.append(" or ");
            }
        }
        sqlStr.append(" ) ");
        List list = this.taskConfDao.list(sqlStr.toString(), params.toArray());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 检测同一人员在同一任务类型、区域是否已经存在
     * @param taskConf
     * @param uid
     * @return true 说明已经存在 false说明不存在
     */
    private boolean checkTaskConfByArea(TCrmCarTaskConf taskConf,String uid) throws Exception {
        List list=this.taskConfDao.list("select * from T_CRM_TASK_CONF where task_p_code=? " +
                "and task_c_code=? and u_id=? and company_id=? and task_type=? and o_area=? and o_area_second=?",
                StringUtil.formatEmpty(taskConf.getTaskPCode()),StringUtil.formatEmpty(taskConf.getTaskCCode()),
                StringUtil.formatEmpty(taskConf.getuId()),StringUtil.formatEmpty(taskConf.getCompanyId()),
                StringUtil.formatEmpty(taskConf.getTaskType()),StringUtil.formatEmpty(taskConf.getoArea()),
                StringUtil.formatEmpty(taskConf.getoAreaSecond()));
        if(list==null){
            return false;
        }else{
            if(list.isEmpty()){
                return false;
            }
            if(list.size()==0){
                return false;
            }
        }
        return true;
    }

    /**
     * @Name： 门店是否已经被分配
     * @Author: Liu XiaoLong
     * @Date: 2017/12/26 15:22
     * @Remark:  true： 已经被分配  false ：没有分配
     */
    private boolean checkTaskConfByStore(TCrmCarTaskConf taskConf) throws Exception {

        String sql = "SELECT * FROM t_crm_task_conf WHERE task_p_code = ? " + // 大类
                "AND task_c_code = ? " + // 小类
                " AND company_id = ? " + // 公司ID
                " AND task_type = ? " + // 权限类型 0管理  1处理
                " AND  store_code = ? "; // 门店代码
        List list=this.taskConfDao.list(sql,
                StringUtil.formatEmpty(taskConf.getTaskPCode()),
                StringUtil.formatEmpty(taskConf.getTaskCCode()),
                StringUtil.formatEmpty(taskConf.getCompanyId()),
                StringUtil.formatEmpty(taskConf.getTaskType()),
                StringUtil.formatEmpty(taskConf.getStoreCode()));
        if(list==null){
            return false;
        }else{
            if(list.isEmpty()){
                return false;
            }
            if(list.size()==0){
                return false;
            }
        }

        return true;
    }

    /**
     * 区域资源下 返回指定类型的任务资源
     * @param taskConf
     * @param uid
     * @param confType
     * @return
     * @throws Exception
     */
    private List getTaskConfByArea(TCrmCarTaskConf taskConf,String uid,String confType) throws Exception {
        List list=this.taskConfDao.list("select * from T_CRM_TASK_CONF where task_p_code=? " +
                        "and task_c_code=? and conf_type=? and company_id=? and task_type=? and o_area=? and o_area_second=?",
                StringUtil.formatEmpty(taskConf.getTaskPCode()),StringUtil.formatEmpty(taskConf.getTaskCCode()),
                !"".equals(confType)?confType:StringUtil.formatEmpty(taskConf.getConfType()),
                StringUtil.formatEmpty(taskConf.getCompanyId()),
                StringUtil.formatEmpty(taskConf.getTaskType()),StringUtil.formatEmpty(taskConf.getoArea()),
                StringUtil.formatEmpty(taskConf.getoAreaSecond()));
        return list;
    }

    /**
     * 尾数 尾号　vin录入时排除自身以及未分配，查看是否还有其它类型，如果有则不允许录入
     * @param taskConf
     * @param WFP
     * @param companyId
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByWHAndWSAndVinAdnArea(TCrmCarTaskConf taskConf, String WFP, String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where task_p_code=? and task_c_code=? and conf_type<>? " +
                "and conf_type<>? and task_type=? and from_car='0' and company_id=? and o_area=? and o_area_second=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                WFP, taskConf.getConfType(), String.valueOf(TASK_POWER.C.ordinal()), companyId,
                StringUtil.formatEmpty(taskConf.getoArea()),
                StringUtil.formatEmpty(taskConf.getoAreaSecond()));
        if (list.size() > 0) {
            return true;
        }
        return false;
    }
    //---------------------------------------快修任务分配结束-------------------------------------------------------------
    /**
     * 保存任务分配资源
     * 1、验证人员是否已经存在
     * 2、验证任务类型是否已经存在分配
     * 3、
     *
     * @param taskConf
     * @param uid
     */
    @Override
    public void saveTaskConf(TCrmCarTaskConf taskConf, String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        taskConf.setCompanyId(companyId);
        this.updTaskPcode(taskConf);
        if (taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))) {
            //1、新增全部类型 判断是否已经存在全部
            if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_ALL)) {
                //1、判断人员是否已经在该任务类型下分配
                boolean userFlag = this.checkTaskConfByUser(taskConf, uid);
                if (userFlag) {
                    throw new Exception("该人员在任务下已经分配资源，请勿重复分配!!");
                }
                //1、判断是否已经有全部类型
                boolean flag = this.checkTaskConfExistConfType(taskConf, Constant.DISTCARTYPE.CAR_ALL, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[全部]任务资源，请勿重复分配!!");
                }
                //2、判断是否有其它类型
                flag = this.checkTaskConfNoExistByAll(taskConf, Constant.DISTCARTYPE.CAR_ALL, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在其它类别任务资源，请调整后重新分配!!");
                }
                //3、判断是否有遵循车辆档案
                flag = this.checkTaskConfByFromCar(taskConf, String.valueOf(FROM_CAR.YES.ordinal()), companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[遵循车辆档案]任务资源，请调整后重新分配!!");
                }
            }
            //2、遵循车辆档案
            if (taskConf.getFromCar().equals(String.valueOf(FROM_CAR.YES.ordinal()))) {
                //1、判断是否已经存在遵循车辆档案，如果有则不允许在次添加
                boolean flag = this.checkTaskConfByFromCar(taskConf, String.valueOf(FROM_CAR.YES.ordinal()), companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[遵循车辆档案]任务资源，请调整后重新分配!!");
                }
                //2、判断是否有全部类别的资源
                flag = this.checkTaskConfExistConfType(taskConf, Constant.DISTCARTYPE.CAR_ALL, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[全部]任务资源，不允许分配其它类别资源，请调整后重新分配!!");
                }
                //
            }
            //3、分配未分配类别
            if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WFP)) {
                //1、判断人员是否已经在该任务类型下分配
                boolean userFlag = this.checkTaskConfByUser(taskConf, uid);
                if (userFlag) {
                    throw new Exception("该人员在任务下已经分配资源，请勿重复分配!!");
                }
                //1、判断是否有全部任务类别
                boolean flag = this.checkTaskConfExistConfType(taskConf, Constant.DISTCARTYPE.CAR_ALL, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[全部]任务资源，不允许分配其它类别资源，请调整后重新分配!!");
                }
                //2、判断是否已经有未分配任务类别
                flag = this.checkTaskConfExistConfType(taskConf, Constant.DISTCARTYPE.CAR_WFP, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[未分配车辆]任务资源，请调整后重新分配!!");
                }
            }
            //4、尾号、尾数、VIN
            if (taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WH) ||
                    taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_WS) ||
                    taskConf.getConfType().equals(Constant.DISTCARTYPE.CAR_VIN)) {
                //1、判断人员是否已经在该任务类型下分配
                boolean userFlag = this.checkTaskConfByUser(taskConf, uid);
                if (userFlag) {
                    throw new Exception("该人员在任务下已经分配资源，请勿重复分配!!");
                }
                //1、判断是否有全部类别 ，如果有全部则不在分配
                boolean flag = this.checkTaskConfExistConfType(taskConf, Constant.DISTCARTYPE.CAR_ALL, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在[全部]任务资源，不允许分配其它类别资源，请调整后重新分配!!");
                }
                //2、判断除了本类别之外，是否有其它类别（不包含未分配车辆，以及遵循车辆档案） 如果有则不允许添加
                flag = this.checkTaskConfByWHAndWSAndVin(taskConf, Constant.DISTCARTYPE.CAR_WFP, companyId);
                if (flag) {
                    throw new Exception("该任务类型下，已经存在其它任务资源，请调整后重新分配!!");
                }

            }
        }
        //管理权限 判断是否已经存在
        if (taskConf.getTaskType().equals(String.valueOf(TASK_POWER.G.ordinal()))) {
            boolean flag = this.checkTaskPower(taskConf, uid);
            if (flag) {
                throw new Exception("该角色已经分配管理规则，请调整后重试!!");
            }
        }
        this.save(taskConf, uid);
    }

    //-----------------------------------全部资源类别判断--------------------------------------------

    /**
     * 判断是否已经含有某个任务资源类型
     *
     * @param taskConf
     * @return
     */
    private boolean checkTaskConfExistConfType(TCrmCarTaskConf taskConf, String confType, String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where task_p_code=? and task_c_code=? and task_type=? and conf_type=? and company_id=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getTaskType(), confType, companyId);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断除全部以外 还有没有其它任务类别，如果有 不允许 添加
     *
     * @param taskConf
     * @return
     */
    private boolean checkTaskConfNoExistByAll(TCrmCarTaskConf taskConf, String confType, String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where task_p_code=? and task_c_code=? and task_type=? and conf_type<>? and company_id=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getTaskType(), confType, companyId);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断该任务类别下是否有遵循车辆档案
     *
     * @param taskConf
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByFromCar2(TCrmCarTaskConf taskConf, String fromCar, String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where task_p_code=? and task_c_code=? and task_type=? and from_car=? and company_id=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getTaskType(), fromCar, companyId);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    private boolean checkTaskConfByWHAndWSAndVin(TCrmCarTaskConf taskConf, String WFP, String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where task_p_code=? and task_c_code=? and conf_type<>? " +
                "and conf_type<>? and task_type=? and from_car='0' and company_id=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                WFP, taskConf.getConfType(), String.valueOf(TASK_POWER.C.ordinal()), companyId);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    //-----------------------------------全部资源类别判断结束--------------------------------------------
    private void updTaskPcode(TCrmCarTaskConf taskConf) {
        Map<String, String> map = new HashMap<>();
        map.put("cnj", "bx");
        map.put("cns", "bx");
        map.put("xbj", "bx");
        map.put("xbs", "bx");
        map.put("hyt", "bx");
        map.put("fhyt", "bx");
        map.put("jdj", "bx");
        map.put("jds", "bx");
        map.put("sr", "ga");
        map.put("ns", "ga");
        map.put("zbt", "ga");
        //关爱类增加券卡
        map.put("qk", "ga");
        map.put("ybt", "ga");
        map.put("6", "ls");
        map.put("7", "ls");
        map.put("8", "ls");
        map.put("9", "ls");
        map.put("10", "ls");
        map.put("11", "ls");
        map.put("12", "ls");
        map.put("13", "ls");
        map.put("14", "ls");
        map.put("15", "ls");
        map.put("16", "ls");
        map.put("17", "ls");
        map.put("sb_mbr", "by");
        map.put("sb_mby", "by");
        map.put("eb_mbr", "by");
        map.put("eb_mby", "by");
        map.put("db_mbr", "by");
        map.put("db_mby", "by");
        map.put("sy_mbr", "by");
        //自定义由原来key zdy  value zdy
        //改为key zdy value qt
        map.put("zdy", "qt");
        String taskPcode = map.get(taskConf.getTaskCCode());
        taskConf.setTaskPCode(taskPcode);
    }


    /**
     * 保存任务分配资源信息
     *
     * @param taskConf
     * @param uid
     * @throws Exception
     */
    private void save(TCrmCarTaskConf taskConf, String uid) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        taskConf.setCompanyId(companyId);
        if (taskConf.getFromCar().equals(String.valueOf(FROM_CAR.NO.ordinal()))
                &&
                taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))
                ) {
            //验证是否有其它的
            switch (taskConf.getConfType()) {
                case Constant.DISTCARTYPE.CAR_ALL:
                    taskConf.setConfVal("");
                    //选择全部 直接保存
                    break;
                case Constant.DISTCARTYPE.CAR_WH:
                    //1、查看已经分配的数值是否有人已经分配
                    boolean flag = this.checkPlateNum(taskConf.getConfType(), taskConf.getConfVal(), taskConf.getuId(), taskConf.getCompanyId(), taskConf.getTaskPCode(), taskConf.getTaskCCode());
                    //2、没有分配保存车辆分配规则
                    if (flag) {
                        throw new Exception("该人员分配的车牌号已经存在，请调整后重新分配!!");
                    }
                    break;
                case Constant.DISTCARTYPE.CAR_WS:
                    boolean wsFlag = this.checkPlateNum(taskConf.getConfType(), taskConf.getConfVal(), taskConf.getuId(), taskConf.getCompanyId(), taskConf.getTaskPCode(), taskConf.getTaskCCode());
                    //2、没有分配保存车辆分配规则
                    if (wsFlag) {
                        throw new Exception("该人员分配的车牌号已经存在，请调整后重新分配!!");
                    }
                    break;
                case Constant.DISTCARTYPE.CAR_VIN:
                    taskConf.setConfVal("");
                    break;
                case Constant.DISTCARTYPE.CAR_CX:
                    //暂时不操作
                    break;
                case Constant.DISTCARTYPE.CAR_WFP:
                    taskConf.setConfVal("");
                    break;
            }
        }
        taskConfDao.saveOrUpdate(taskConf);
        this.distCarByCarConf(taskConf, uid, null);
//        if(taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))) {
//            //更新任务类型下 未分配全部的序号
//            String sql = "update t_crm_task_conf c1," +
//                    "(select MAX(disp_order) dispOrder from t_crm_task_conf where task_p_code=? and task_c_code=?) c2 " +
//                    "set disp_order=c2.dispOrder+1 where task_p_code=? and task_c_code=? and conf_type='4'";
//            this.taskConfDao.executeSQL(sql, StringUtil.formatNull(taskConf.getTaskPCode()),StringUtil.formatNull( taskConf.getTaskCCode()),
//                    taskConf.getTaskPCode(), taskConf.getTaskCCode());
//        }
    }

    /**
     * 检测任务下 角色是否已经存在管理角色
     *
     * @return
     */
    private boolean checkTaskPower(TCrmCarTaskConf taskConf, String uid) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and role_id=? and task_type=? and company_id=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getRoleId(), taskConf.getTaskType(), TokenUtil.getCompany(uid));
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 验证人员是否已经添加过任务分配资源
     *
     * @param taskConf
     * @return
     */
    private boolean checkTaskConfByUser(TCrmCarTaskConf taskConf, String companyId) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and u_id=? and company_id=? and task_type=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getuId(), companyId, taskConf.getTaskType());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 检测任务下 是否有其它分配的任务类型
     *
     * @param taskConf
     * @param companyId
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByNoTaskType(TCrmCarTaskConf taskConf, String companyId) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and conf_type <>? and company_id=? and task_type=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getConfType(), companyId, taskConf.getTaskType());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 未分配车辆查询
     *
     * @param taskConf
     * @param companyId
     * @param type
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByNoTaskTypeWFP(TCrmCarTaskConf taskConf, String companyId, String type) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and conf_type <>? and conf_type<>?  and company_id=? and task_type=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                taskConf.getConfType(), type, companyId, taskConf.getTaskType());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    private boolean checkTaskConfByFromCar(TCrmCarTaskConf taskConf, String fromCar, String companyId) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and company_id=? and from_car=? and task_type=? and conf_type<>?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                companyId, fromCar, taskConf.getTaskType(), Constant.DISTCARTYPE.CAR_WFP);
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    private boolean checkTaskConfByIsTaskType(TCrmCarTaskConf taskConf, String companyId, String fromCar) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and company_id=? and from_car=? and task_type=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                companyId, fromCar, taskConf.getTaskType());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 遵循车辆档案 验证角色是否重复
     *
     * @param taskConf
     * @param companyId
     * @param fromCar
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByFromCarAndRole(TCrmCarTaskConf taskConf, String companyId, String fromCar) throws Exception {
        String sql = "select * from T_CRM_TASK_CONF where task_p_code=? and task_c_code=? and company_id=? and from_car=? and role_id=? and task_type=?";
        List list = this.taskConfDao.list(sql, StringUtil.formatNull(taskConf.getTaskPCode()), StringUtil.formatNull(taskConf.getTaskCCode()),
                companyId, fromCar, taskConf.getRoleId(), taskConf.getTaskType());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * @param taskConf
     * @param companyId
     * @param confType
     * @return
     * @throws Exception
     */
    private boolean checkTaskConfByTaskType(TCrmCarTaskConf taskConf, String companyId, String confType) throws Exception {
        StringBuffer sql = new StringBuffer();
        List<String> params = new ArrayList<>();
        sql.append("select * from T_CRM_TASK_CONF where company_id=? and conf_type=? and task_type=? ");
        params.add(taskConf.getCompanyId());
        params.add(confType);
        params.add(taskConf.getTaskType());
        if (!StringUtils.isEmpty(taskConf.getTaskPCode())) {
            sql.append(" and task_p_code=? ");
            params.add(taskConf.getTaskPCode());
        }
        if (!StringUtils.isEmpty(taskConf.getTaskCCode())) {
            sql.append(" and task_c_code=? ");
            params.add(taskConf.getTaskCCode());
        }

        List list = this.taskConfDao.list(sql.toString(), params.toArray());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }


    /**
     * 根据车辆分配规则，进行分配车辆
     *
     * @param confId
     * @param uid
     * @param file
     * @throws Exception
     */
    @Override
    public void distCarByCarConf(String confId, String uid, MultipartFile file) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        TCrmCarTaskConf taskConf = this.taskConfDao.getCrmCarConfById(confId, companyId);
        if (taskConf != null) {
            String fromCar=taskConf.getFromCar();

            //判断是否遵循车辆档案分配信息
            if (String.valueOf(FROM_CAR.YES.ordinal()).equals(fromCar)) {
                //将该角色下车辆档案信息拷贝
                this.distCarTaskByCarConf(taskConf);
            } else {
                this.distCarByCarConf(taskConf, uid, file);
            }
        } else {
            throw new Exception("未查询到任务资源分配信息！！");
        }
    }


    /**
     * 保存分配规则，并分配车辆信息
     *
     * @param taskConf
     * @param uid
     * @throws Exception
     */
    private void distCarByCarConf(TCrmCarTaskConf taskConf, String uid, MultipartFile file) throws Exception {
        switch (taskConf.getConfType()) {
            case Constant.DISTCARTYPE.CAR_ALL:
                //选择全部 直接保存
//                this.saveCrmCar(carConf,uid);
                break;
            case Constant.DISTCARTYPE.CAR_WH:
                //车辆尾号
                this.distCarByPlateNum(taskConf, uid);
                break;
            case Constant.DISTCARTYPE.CAR_WS:
                //车辆尾数
                this.distCarByPlateNum(taskConf, uid);
                break;
            case Constant.DISTCARTYPE.CAR_VIN:
                if (file != null) {
                    this.disCarByVin(file, taskConf, uid);
                }
                break;
            case Constant.DISTCARTYPE.CAR_CX:
                //暂时不操作
                break;
            case Constant.DISTCARTYPE.CAR_WFP:
                //未分配
//                this.disCarByWfp(taskConf,uid);
                break;
        }
    }

    //---------------------------------车辆档案分配开始---------------------------
    public void distCarTaskByCarConf(TCrmCarTaskConf taskConf) throws Exception {
        //1、获得该角色对应的档案分配信息
        List<TCrmCarConf> crmCarConfs = tcrmCarConfService.getCrmCarConfByRoleId(taskConf.getRoleId(), taskConf.getCompanyId());
        //2、判断是否有车辆分配信息
        if (crmCarConfs.size() > 0) {
            //3、先删除任务资源中的本地规则
            String delsql = "delete from t_crm_task_conf_detail where task_p_code =? and task_c_code=? and role_id=? and company_id=?";
            this.taskConfDao.executeSQL(delsql, taskConf.getTaskPCode(), taskConf.getTaskCCode(), taskConf.getRoleId(), taskConf.getCompanyId());
            //4、遍历生成 全部的排除在外
            int i = 0;
            for (TCrmCarConf carconf : crmCarConfs) {
                if (!carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_ALL)) {
                    StringBuffer inssql = new StringBuffer();
                    inssql.append("insert into t_crm_task_conf_detail(id,company_id,role_id,task_c_code,task_p_code,u_id,vin)");
                    inssql.append("select replace(t.id,'-','') id,t.company_id,t.role_id,'" + taskConf.getTaskCCode() + "','" + taskConf.getTaskPCode() + "',u_id,vin from ( " +
                            "select UUID() id,company_id,role_id,u_id,vin from t_crm_car_conf_detail where company_id=? and role_id=? and u_id=?)t");
//                            "select id,company_id,role_id,'"+taskConf.getTaskCCode()+"','"+taskConf.getTaskPCode()+
//                            "',u_id,vin from t_crm_car_conf_detail where company_id=? and role_id=? and u_id=?";
                    this.taskConfDao.executeSQL(inssql.toString(), carconf.getCompanyId(), carconf.getRoleId(), carconf.getuId());
                } else {
                    i++;
                }
            }
            if (i > 0) {
                throw new Exception("该角色对应的车辆分配档案为[全部]资源且分配了多名工作人员!!");
            }
        } else {
            throw new Exception("该角色未分配车辆资源!!");
        }
    }

    //---------------------------------车辆档案分配结束---------------------------
    //---------------------------------车辆尾号、尾数分配开始---------------------------

    private void distCarByPlateNum(TCrmCarTaskConf taskConf, String uid) throws Exception {
        this.savePlateNumDetail(taskConf);
    }

    /**
     * 根据车辆分配规则 分配其所选信息
     *
     * @param taskConf
     * @throws Exception
     */
    public void savePlateNumDetail(TCrmCarTaskConf taskConf) throws Exception {
        //车辆分配值，车属号 或车尾数，vin时 另行处理
        String refValue = taskConf.getConfVal().replaceAll(",", "");
        //根据类型取车辆
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append(" insert into T_CRM_TASK_CONF_DETAIL(id,company_id,role_id,u_id,vin,task_p_code,task_c_code) ");
        sqlStr.append(" select REPLACE(id,'-','') id,'" + taskConf.getCompanyId() + "','" + taskConf.getRoleId() + "' ,'" + taskConf.getuId() +
                "',vin,'" + taskConf.getTaskPCode() + "','" + taskConf.getTaskCCode() + "' from ( ");
        sqlStr.append(" select UUID() id,vin from t_crm_car c where c.company_id=? ");
        params.add(taskConf.getCompanyId());
        switch (taskConf.getConfType()) {
            case Constant.DISTCARTYPE.CAR_WH:
                sqlStr.append(" AND  c.plate_num REGEXP ? ");
                params.add("[" + refValue + "]$");
                break;
            case Constant.DISTCARTYPE.CAR_WS:
                //先不写
                sqlStr.append(" AND c.plate_num REGEXP ? ");
                params.add(".*[" + refValue + "][A-Za-z]*$");
                //根据尾数查询
                break;
        }
        sqlStr.append(" AND NOT EXISTS(select * from T_CRM_TASK_CONF_DETAIL where c.vin=vin and role_id=? and company_id=? and task_p_code=? and task_c_code=?) ");
        params.add(taskConf.getRoleId());
        params.add(taskConf.getCompanyId());
        params.add(taskConf.getTaskPCode());
        params.add(taskConf.getTaskCCode());
        sqlStr.append(" )t ");
        int i = this.taskConfDao.executeSQL(sqlStr.toString(), params.toArray());
    }

    /**
     * 检测该该任务类型下，车牌尾数或尾号 是否有重复分配
     *
     * @param refType
     * @param refValue
     * @param userId
     * @param companyId
     * @param typePCode
     * @param typeCCode
     * @return
     * @throws Exception
     */
    public boolean checkPlateNum(String refType, String refValue, String userId, String companyId, String typePCode, String typeCCode) throws Exception {
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append(" select * from  T_CRM_TASK_CONF where company_id=? and conf_type=? and task_p_code=? and task_c_code=? ");
        params.add(companyId);
        params.add(refType);
        params.add(typePCode);
        params.add(typeCCode);
        if (!"".equals(userId)) {
            sqlStr.append(" and u_id<>? ");
            params.add(userId);
        }
        sqlStr.append(" and ( ");
        String[] refValues = refValue.split(",");
        for (int i = 0; i < refValues.length; i++) {
            sqlStr.append(" find_in_set(?,conf_val) ");
            params.add(refValues[i]);
            if (i < (refValues.length - 1)) {
                sqlStr.append(" or ");
            }
        }
        sqlStr.append(" ) ");
        List list = this.taskConfDao.list(sqlStr.toString(), params.toArray());
        if (list.size() > 0) {
            return true;
        }
        return false;
    }

    //---------------------------------车辆尾号、尾数分配结束---------------------------
    //---------------------------------车辆未分配开始---------------------------
    private void disCarByWfp(TCrmCarTaskConf conf, String uid) throws Exception {
        //1、保存车辆分配信息
//        conf=this.saveCrmCar(conf,uid);
        //2、根据分配规则明细中的角色信息、车辆信息查询出所有未分配的车辆
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append(" insert into T_CRM_TASK_CONF_DETAIL(id,company_id,role_id,u_id,vin,task_p_code,task_c_code) ");
        sqlStr.append(" select REPLACE(id,'-','') id,'" + conf.getCompanyId() + "','" + conf.getRoleId() + "' ,'" + conf.getuId() +
                "',vin,'" + conf.getTaskPCode() + "','" + conf.getTaskCCode() + "' from ( ");
        sqlStr.append(" select UUID() id,vin from t_crm_car c where c.company_id=? ");
        params.add(conf.getCompanyId());
        sqlStr.append(" AND NOT EXISTS(select * from T_CRM_TASK_CONF_DETAIL where car.vin=vin and role_id=? and company_id=? and task_p_code=? and task_c_code=?) ");
        params.add(conf.getRoleId());
        params.add(conf.getCompanyId());
        params.add(conf.getTaskPCode());
        params.add(conf.getTaskCCode());
        this.taskConfDao.executeSQL(sqlStr.toString(), params.toArray());
    }

    //---------------------------------车辆未分配结束---------------------------
    //---------------------------------车辆VIN分配开始---------------------------
    private void disCarByVin(MultipartFile file, TCrmCarTaskConf taskConf, String uid) throws Exception {
        //1、保存车辆分配规则
//        carConf=this.saveCrmCar(carConf,uid);
        //2、解析Vin资源
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (fileType != null && (fileType.endsWith("xlsx") || fileType.endsWith("xls"))) {
            List<TCrmCarConfExcelTemp> excelTemps = tcrmCarConfService.readExcel(file, uid, taskConf.getId());
            //3、删除该分配规则资源下的VIn号
            this.delExcelTempByConf(taskConf);
            //4、保存分配的Vin资源
            this.taskConfDao.saveOrUpdateList(excelTemps);
            //5、插入分配详细
            this.saveVinDetail(taskConf);
            //6、删除本次VIN分配明细资源
            this.delExcelTempByConf(taskConf);
        } else {
            throw new Exception("无法识别的文件格式！");
        }
    }

    /**
     * 分配VIN车辆资源
     *
     * @param carConf
     * @throws Exception
     */
    private void saveVinDetail(TCrmCarTaskConf carConf) throws Exception {
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append(" insert into T_CRM_TASK_CONF_DETAIL(id,company_id,role_id,u_id,vin,task_p_code,task_c_code) ");
        sqlStr.append(" select REPLACE(id,'-','') id,'" + carConf.getCompanyId() + "','" + carConf.getRoleId() + "' ,'" + carConf.getuId() +
                "',vin,'" + carConf.getTaskPCode() + "','" + carConf.getTaskCCode() + "'  from ( ");
        sqlStr.append(" select UUID() id,vin from t_crm_car c where c.company_id=? ");
        params.add(carConf.getCompanyId());
        sqlStr.append(" AND EXISTS(select * from t_crm_car_conf_excel_temp where vin=c.vin and config_id=?) ");
        params.add(carConf.getId());
        sqlStr.append(" AND not EXISTS (select * from T_CRM_TASK_CONF_DETAIL where company_id=? and role_id=? and vin=c.vin and task_p_code=? and task_c_code=?) ");
        params.add(carConf.getCompanyId());
        params.add(carConf.getRoleId());
        params.add(carConf.getTaskPCode());
        params.add(carConf.getTaskCCode());
        sqlStr.append(")t");
        this.taskConfDao.executeSQL(sqlStr.toString(), params.toArray());
    }

    /**
     * 删除分配的VIN资源信息
     *
     * @param carConf
     * @throws Exception
     */
    private void delExcelTempByConf(TCrmCarTaskConf carConf) throws Exception {
        String sql = "delete from T_CRM_CAR_CONF_EXCEL_TEMP where config_id=?";
        this.taskConfDao.executeSQL(sql, carConf.getId());
    }
    //---------------------------------车辆VIN分配结束---------------------------

    @Override
    public Map page(String pcode, String code, String uid, String start, String limit) throws Exception {
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append("select t.*,u.u_name,o.label areaName,o2.label areaSecondName from (");
        sqlStr.append(" select conf.*,role.r_name from  T_CRM_TASK_CONF conf," +
                "t_bc_role role " +
                "where conf.role_id=role.id ");
        sqlStr.append(" and conf.company_id=? ");
        params.add(TokenUtil.getCompanyId(uid));
        if (!StringUtils.isEmpty(pcode)) {
            sqlStr.append(" and conf.task_p_code=? ");
            params.add(pcode);
        }
        if (!StringUtils.isEmpty(code)) {
            sqlStr.append(" and conf.task_c_code=? ");
            params.add(code);
        }
        sqlStr.append(")t " +
                "LEFT JOIN t_bc_user u " +
                "ON " +
                "t.u_id=u.id");
        sqlStr.append(" left join (select * from t_bc_newdict where p_code='area') o on t.o_area=o.code " +
                " left join (select * from t_bc_newdict where p_code in (select code from " +
                " t_bc_newdict where p_code='area')) o2 on t.o_area_second=o2.code");
        return taskConfDao.page(sqlStr.toString(), params.toArray(), start, limit);
    }

    /**
     * 删除任务分配资源信息
     *
     * @param id
     * @param uid
     * @throws Exception
     */
    @Override
    public void delTaskConf(String id, String uid) throws Exception {
        TCrmCarTaskConf taskConf = taskConfDao.getCrmCarConfById(id, TokenUtil.getCompanyId(uid));
        if (taskConf == null) {
            throw new Exception("未找到任务资源!!");
        }
        //如果为管理状态 直接删除
        if (taskConf.getTaskType().equals(String.valueOf(TASK_POWER.C.ordinal()))) {
            if (taskConf.getFromCar().equals(String.valueOf(FROM_CAR.YES.ordinal()))) {
                //获得其对应的车辆档案信息
                List<TCrmCarConf> crmCarConfList = this.tcrmCarConfService.getCrmCarConfByRoleId(taskConf.getRoleId(), taskConf.getCompanyId());
                for (TCrmCarConf conf : crmCarConfList) {
                    this.delAndUpdTaskInfo(taskConf, conf.getuId());
                }
            } else {
                this.delAndUpdTaskInfo(taskConf, taskConf.getuId());
            }
        }
        //删除配置信息
        String sql = "delete from T_CRM_TASK_CONF where id=?";
        this.taskConfDao.executeSQL(sql, taskConf.getId());
    }

    private void delAndUpdTaskInfo(TCrmCarTaskConf taskConf, String uid) throws Exception {

        //更新任务表中的数据，将已经分配的任务、未完成的said更新为未分配
        StringBuffer sqlStr = new StringBuffer();
        List<String> params = new ArrayList<>();
        sqlStr.append("update t_crm_task_real set sa_id = null where type_pcode=? and type_code=? and sa_id=? and company_id=? and `status`=0 ");
//         and EXISTS( " +
//                "select * from t_crm_task_conf_detail where role_id=? and u_id=? and task_p_code=? and task_c_code=? ) ");
        params.add(taskConf.getTaskPCode());
        params.add(taskConf.getTaskCCode());
        params.add(uid);
        params.add(TokenUtil.getCompanyId(uid));
//        params.add(taskConf.getRoleId());
//        params.add(uid);
//        params.add(taskConf.getTaskPCode());
//        params.add(taskConf.getTaskCCode());
        this.taskConfDao.executeSQL(sqlStr.toString(), params.toArray());
        //移除分配的资源信息
        this.delTaskConfDetail(taskConf);
    }


    private void delTaskConfDetail(TCrmCarTaskConf taskConf) throws Exception {
        List<String> params = new ArrayList<>();
        String sql = "delete from t_crm_task_conf_detail where role_id=? and u_id=? and task_p_code=? and task_c_code=? ";
        params.add(taskConf.getRoleId());
        params.add(taskConf.getuId());
        params.add(taskConf.getTaskPCode());
        params.add(taskConf.getTaskCCode());
        int i = this.taskConfDao.executeSQL(sql, params.toArray());
    }


    /**
     * 任务分配更新信息
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public Integer distTaskByTaskConf(String companyId) throws Exception {
        Integer sum = 0;
        /**1、遵循车辆档案的*/
        // --全部类型
        sum += this.distTaskByCarConf(companyId);

        /**2、不遵循车辆档案的*/
        //--全部
        sum += this.distTaskByTaskConfAll(companyId);
        //--尾号、尾数、VIN
        this.disTaskByTaskConfAndWHAndWSAndVIN(companyId);
        //--剩余车辆
        sum += this.distTaskByTaskConfWFP(companyId);
        return sum;
    }


    private Integer disTaskByTaskConfAndWHAndWSAndVIN(String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where company_id=? and task_type=? and conf_type in (?,?,?)";
        List<Map<String, Object>> list = this.taskConfDao.list(sql, companyId, String.valueOf(TASK_POWER.C.ordinal()),
                Constant.DISTCARTYPE.CAR_WS,Constant.DISTCARTYPE.CAR_WH,Constant.DISTCARTYPE.CAR_VIN);
        for(int i=0;i<list.size();i++){
            Map map=list.get(i);
            StringBuffer sqlStr=new StringBuffer();
            sqlStr.append(" update t_crm_task_real set sa_id=? where company_id=? and type_pcode=? and type_code=? and store_p_area=?" +
                    " and store_area=? and (sa_id=null or sa_id ='') ");
            List<Object> params=new ArrayList<>();
            params.add(StringUtil.formatEmpty(map.get("uId")));
            params.add(StringUtil.formatEmpty(map.get("companyId")));
            params.add(StringUtil.formatEmpty(map.get("taskPCode")));
            params.add(StringUtil.formatEmpty(map.get("taskCCode")));
            params.add(StringUtil.formatEmpty(map.get("oArea")));
            params.add(StringUtil.formatEmpty(map.get("oAreaSecond")));
            String refValue=StringUtil.formatEmpty(map.get("confVal"));
            //获取车辆分配类型
            String confType=StringUtil.formatEmpty(map.get("confType"));
            switch (confType){
                case Constant.DISTCARTYPE.CAR_WH:
                    sqlStr.append(" AND  plateNum REGEXP ? ");
                    params.add("[" + refValue + "]$");
                    break;
                case Constant.DISTCARTYPE.CAR_WS:
                    //先不写
                    sqlStr.append(" AND plateNum REGEXP ? ");
                    params.add(".*[" + refValue + "][A-Za-z]*$");
                case Constant.DISTCARTYPE.CAR_VIN:
                    this.distTaskByTaskConfDetail(companyId);
                    break;
            }
            this.taskConfDao.executeSQL(sqlStr.toString(),params.toArray());
        }
        return 0;
    }



    private Integer distTaskByTaskConfWFP(String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where company_id=? and task_type=? and conf_type=?";
        List<Map<String, Object>> list = this.taskConfDao.list(sql, companyId, String.valueOf(TASK_POWER.C.ordinal()), Constant.DISTCARTYPE.CAR_WFP);
        Integer sum = 0;
        for (Map map : list) {
            sum += this.distTaskByAllSql(map, companyId);
        }
        return sum;
    }


    /**
     * 任务资源分配类型为全部
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    private Integer distTaskByTaskConfAll(String companyId) throws Exception {
        String sql = "select * from t_crm_task_conf where company_id=? and task_type=? and conf_type=?";
        List<Map<String, Object>> list = this.taskConfDao.list(sql, companyId, String.valueOf(TASK_POWER.C.ordinal()), Constant.DISTCARTYPE.CAR_ALL);
        Integer sum = 0;
        //逐条遍历
        for (Map map : list) {
            sum += this.distTaskByAllSql(map, companyId);
        }
        return sum;
    }

    /**
     * 遵循车辆信息，角色为全部车辆，全部车辆如果为1人时，直接更新
     * 如果为多人时 不做处理
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    private Integer distTaskByCarConf(String companyId) throws Exception {
        Integer sum = 0;
        String sql = "select * from t_crm_task_conf where company_id=? and from_car=? and task_type=? ";
        List<Map<String, Object>> list = this.taskConfDao.list(sql, companyId, String.valueOf(FROM_CAR.YES.ordinal()), String.valueOf(TASK_POWER.C.ordinal()));
        //逐条遍历
        for (Map map : list) {
            String roleId = String.valueOf(map.get("roleId"));
            List<TCrmCarConf> crmCarConfs = tcrmCarConfService.getCrmCarConfByRoleId(roleId, companyId);
            int all = 0;

            // 分配类型
            for (TCrmCarConf carconf : crmCarConfs) {
                if (carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_WH) ||    /// 尾号、尾数、vin
                        carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_WS) ||
                        carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_VIN)) {
                    sum += this.distTaskByWHAndWsAdnVINSql(map, companyId, carconf);
                }
                if (carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_ALL)) {   // 全部
                    all++;
                }

                if (carconf.getConfType().equals(Constant.DISTCARTYPE.CAR_WFP)) { //未分配车辆
                    sum += this.distTaskByWFPSql(map, companyId, carconf);
                }
            }
            //判断全部有几人 如果有一人 则分配任务 如果有多人 则不处理
            if (all == 1) { // 有一个人
                sum += this.distTaskByAllSql(map, companyId);
            }
        }
        return sum;
    }

    private Integer distTaskByAllSql(Map<String, Object> map, String companyId) throws Exception {
        String uId = String.valueOf(map.get("uId"));
        String typePCode = String.valueOf(map.get("taskPCode"));
        String typeCCode = String.valueOf(map.get("taskCCode"));
        List<Object> params=new ArrayList<>();
        StringBuffer updTaskSql = new StringBuffer("update t_crm_task_real task set task.sa_id=? where task.type_pcode=? and task.type_code=? and task.company_id=?  " +
                "AND (task.sa_id is null or task.sa_id ='') ");



        params.add(uId);
        params.add(typePCode);
        params.add(typeCCode);
        params.add(companyId);

        if(typeCCode.equals("xbj") || typeCCode.equals("xbs")){ // 如果是续保
            updTaskSql.append(" AND task.store_code = ? ");
            params.add(map.get("storeCode"));
        }


        if(!"".equals(StringUtil.formatEmpty(map.get("oArea")))){
            updTaskSql.append(" and task.store_p_area_code=? ");
            params.add(StringUtil.formatEmpty(map.get("oArea")));
        }
        if(!"".equals(StringUtil.formatEmpty(map.get("oAreaSecond")))){
            updTaskSql.append(" and task.store_area_code=? ");
            params.add(StringUtil.formatEmpty(map.get("oAreaSecond")));
        }
        return this.taskConfDao.executeSQL(updTaskSql.toString(), params.toArray());
    }

    /**
     * 遵循车辆档案 ，根据车辆档案中的VIN进行分配 任务
     * @param map
     * @param companyId
     * @param carConf
     * @return
     * @throws Exception
     */
    private Integer distTaskByWHAndWsAdnVINSql(Map<String, Object> map, String companyId, TCrmCarConf carConf) throws Exception {
        StringBuffer sql = new StringBuffer();
        List<String> params = new ArrayList<>();
        String uId = String.valueOf(map.get("uId"));
        String typePCode = String.valueOf(map.get("taskPCode"));
        String typeCCode = String.valueOf(map.get("taskCCode"));
        sql.append(" update t_crm_task_real task, " +
                " (select * from t_crm_car_conf_detail where role_id=?  " +
                " and u_id=? and company_id=? " +
                " ) t set task.sa_id= ? " +
                " where task.vin=t.vin and task.company_id=? and task.type_pcode=? and task.type_code=? " +
//                "AND task.`status`='0' " +
                "AND task.sa_id is null ");
        params.add(carConf.getRoleId());
        params.add(carConf.getuId());
        params.add(carConf.getCompanyId());
        params.add(carConf.getuId());
        params.add(carConf.getCompanyId());
        params.add(typePCode);
        params.add(typeCCode);
        return this.taskConfDao.executeSQL(sql.toString(), params.toArray());
    }

    /**
     * 遵循车辆未分配车辆
     *
     * @param map
     * @param companyId
     * @param carConf
     * @return
     * @throws Exception
     */
    private Integer distTaskByWFPSql(Map<String, Object> map, String companyId, TCrmCarConf carConf) throws Exception {
        StringBuffer sql = new StringBuffer();
        List<String> params = new ArrayList<>();
        String uId = String.valueOf(map.get("uId"));
        String typePCode = String.valueOf(map.get("taskPCode"));
        String typeCCode = String.valueOf(map.get("taskCCode"));
        sql.append("update t_crm_task_real task, " +
                "( select * from t_crm_car car where car.company_id=? and not EXISTS( " +
                "select * from t_crm_car_conf_detail where car.vin=vin and role_id=? and company_id=? and u_id=? " +
                ") ) t set task.sa_id=? " +
                "where task.vin=t.vin and task.company_id=? and task.type_pcode=? and task.type_code=? " +
//                "AND task.`status`='0' " +
                "AND task.sa_id is null");
        params.add(companyId);
        params.add(carConf.getRoleId());
        params.add(companyId);
        params.add(carConf.getuId());
        params.add(carConf.getuId());
        params.add(companyId);
        params.add(typePCode);
        params.add(typeCCode);
        return this.taskConfDao.executeSQL(sql.toString(), params.toArray());
    }

    /**
     * 尾号、尾数、vin、遵循车辆已经将任务对应的车辆信息存储，直接更新
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    private Integer distTaskByTaskConfDetail(String companyId) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("update  " +
                "t_crm_task_real task, " +
                "t_crm_task_conf_detail detail " +
                "SET task.sa_id=detail.u_id " +
                "WHERE " +
                "task.type_pcode = detail.task_p_code " +
                "AND task.type_code = detail.task_c_code " +
                "AND task.vin = detail.vin " +
                "AND detail.company_id = ? " +
//                "AND task.`status`='0' " +
                "AND task.sa_id is null ");
        return this.taskConfDao.executeSQL(sql.toString(), companyId);
    }

    /**
     * 获得管理权限下的任务类型信息
     *
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getManageTaskTypeByTaskType(String uid, List<String> params) throws Exception {
        String companyId = TokenUtil.getCompanyId(uid);
        StringBuffer sql = new StringBuffer();
        List<String> manageParams = new ArrayList<>();
        sql.append("select * from t_crm_task_conf where company_id=? and task_type=?");
        manageParams.add(companyId);
        manageParams.add(String.valueOf(TASK_POWER.G.ordinal()));
        sql.append("and role_id in (");
        for (int i = 0; i < params.size(); i++) {
            sql.append("?");
            manageParams.add(params.get(i));
            if (i < (params.size() - 1)) {
                sql.append(",");
            }
        }
        sql.append(")");
        return this.taskConfDao.list(sql.toString(), manageParams.toArray());
    }

}
